package com.sls.web.manager.interceptor;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.sls.core.common.KeyUtil;
import com.sls.web.manager.common.Constants;
import com.sls.web.manager.common.UserInfoThreadLocal;
import com.sls.web.manager.execption.KickedOutException;
import com.sls.web.manager.freemarker.CustomFreemarkerManager;
import com.sls.web.manager.pojo.UserInfoVO;
import com.sls.web.manager.sys.service.MenuBuildService;
import com.whalin.MemCached.MemCachedClient;

public class RightsInterceptor implements Interceptor {
	private static final long serialVersionUID = 8109886567899928146L;
	private static final Logger log = Logger.getLogger(RightsInterceptor.class);
	@Resource(name = "menuBuildService")
	private MenuBuildService menuBuildService;
	@Resource(name = "memcachedClient")
	private MemCachedClient memCachedClient;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init() {
		menuBuildService.rightsMenu();
	}

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Cookie[] cookies = ServletActionContext.getRequest().getCookies();
		UserInfoVO op = null;
		UserInfoVO vo = new UserInfoVO();
		String web_cookie_path = CustomFreemarkerManager.getCookiePath();
		String sessionId = null;
		if (cookies != null)
			for (Cookie cookie : cookies) {
				// 用户登录信息
				if (CustomFreemarkerManager.getCookieName(
						Constants.COOKIE_NAME_USERINFO)
						.equals(cookie.getName())) {
					String cookieInfo = cookie.getValue();
					Object object = memCachedClient.get(KeyUtil
							.cookieDencrypt(cookieInfo));
					if (object instanceof UserInfoVO) {
						op = (UserInfoVO) object;
						String uuid = Constants.COOKIE_NAME_USERINFO
								+ op.getUserId();
						// 设置超时
						memCachedClient.set(uuid, op, new Date(30 * 60 * 1000));
					}
				}
				// 用户登录编号
				else if (CustomFreemarkerManager.getCookieName(
						Constants.SESSION_ID).equals(cookie.getName())) {
					sessionId = cookie.getValue();
				}
				// 验证码
				else if (CustomFreemarkerManager.getCookieName(
						Constants.COOKIE_NAME_RANDOMCODE).equals(
						cookie.getName())) {
					ActionContext.getContext()
							.put(Constants.COOKIE_NAME_RANDOMCODE,
									cookie.getValue());
					cookie = new Cookie(cookie.getName(), null);
					cookie.setPath(web_cookie_path);
					cookie.setMaxAge(0);
					ServletActionContext.getResponse().addCookie(cookie);
				}
			}
		vo.setCurrentIp(getIpAddr(ServletActionContext.getRequest()));
		if (op != null && StringUtils.isNotBlank(sessionId)
				&& StringUtils.isNotBlank(op.getLoginTmpId())
				&& !sessionId.equals(op.getLoginTmpId())) {
			if (!(invocation.getProxy().getActionName().equals("login") && (invocation
					.getProxy().getMethod().equals("login")
					|| (invocation.getProxy().getMethod().equals("ssoCheck")) || (invocation
					.getProxy().getMethod().equals("index"))))) {
				log.debug("用户在别的地方登录被迫退出");
				// 是否是异步的ajax请求
				if (this.isAjaxRequest(ServletActionContext.getRequest())) {
					invocation.getInvocationContext().put("message",
							"kickedout");
					return "ajax";
				} else {
					invocation.getInvocationContext().put("login_error",
							"用户在别的地方登录被迫退出");
					throw new KickedOutException("用户在别的地方登录被迫退出");
				}
			}
		}
		// 没有登录先登录
		if (op == null
				&& !(invocation.getProxy().getActionName().equals("login") && (invocation
						.getProxy().getMethod().equals("login")
						|| (invocation.getProxy().getMethod().equals("index"))
						|| (invocation.getProxy().getMethod()
								.equals("ssoCheck"))
						|| (invocation.getProxy().getMethod().equals("main")) || (invocation
						.getProxy().getMethod().equals("header"))))) {
			log.debug("请先登录");
			// 是否是异步的ajax请求
			if (this.isAjaxRequest(ServletActionContext.getRequest())) {
				invocation.getInvocationContext().put("message", "needlogin");
				return "ajax";
			} else {
				invocation.getInvocationContext().put("login_error", "请先登录");
				throw new KickedOutException("请先登录");
			}
		}
		if (op != null) {
			vo.setUserId(op.getUserId());
			vo.setType(op.getType());
			vo.setServiceCode(op.getServiceCode());
			vo.setUserName(op.getUserName());
		}
		UserInfoThreadLocal.set(vo);
		String result = null;
		try {
			result = invocation.invoke();
		} catch (Exception e) {
			log.error(invocation.getAction() + "执行出错", e);
			throw e;
		} finally {
			UserInfoThreadLocal.clean();
		}
		return result;
	}

	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 是否是异步的ajax请求
	 * 
	 * @param request
	 * @return
	 */
	private boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equals(header))
			return true;
		else
			return false;
	}
}
